<?php
class Application_util_BeanJSONDecoder extends Zend_Json_Decoder {

	public static function decode($source = null, $objectDecodeType = Zend_Json::TYPE_ARRAY)
	{
		if (null === $source) {
			require_once 'Zend/Json/Exception.php';
			throw new Zend_Json_Exception('Must specify JSON encoded source for decoding');
		} elseif (!is_string($source)) {
			require_once 'Zend/Json/Exception.php';
			throw new Zend_Json_Exception('Can only decode JSON encoded strings');
		}

		$decoder = new self($source, $objectDecodeType);

		return $decoder->_decodeValue();
	}

	protected function _decodeObject()
	{
		$members = array();
		$tok = $this->_getNextToken();

		while ($tok && $tok != self::RBRACE) {
			if ($tok != self::DATUM || ! is_string($this->_tokenValue)) {
				require_once 'Zend/Json/Exception.php';
				throw new Zend_Json_Exception('Missing key in object encoding: ' . $this->_source);
			}

			$key = $this->_tokenValue;
			$tok = $this->_getNextToken();

			if ($tok != self::COLON) {
				require_once 'Zend/Json/Exception.php';
				throw new Zend_Json_Exception('Missing ":" in object encoding: ' . $this->_source);
			}

			$tok = $this->_getNextToken();
			$members[$key] = $this->_decodeValue();
			$tok = $this->_token;

			if ($tok == self::RBRACE) {
				break;
			}

			if ($tok != self::COMMA) {
				require_once 'Zend/Json/Exception.php';
				throw new Zend_Json_Exception('Missing "," in object encoding: ' . $this->_source);
			}

			$tok = $this->_getNextToken();
		}
		switch ($this->_decodeType) {
			case Zend_Json::TYPE_OBJECT:
				// Create new StdClass and populate with $members
				$result = new $members['__className']();
				unset($members['__className']);
				foreach ($members as $key => $value) {
					$setter = 'set'.ucfirst($key);
					$result->$setter($value);
				}
				break;
			case Zend_Json::TYPE_ARRAY:
			default:
				$result = $members;
				break;
		}

		$this->_getNextToken();
		return $result;
	}

}